package com.atguigu.web.admin.service.impl;

import com.atguigu.common.exception.LeaseException;
import com.atguigu.common.constant.RedisConstant;
import com.atguigu.common.result.ResultCodeEnum;
import com.atguigu.common.utils.JwtUtil;
import com.atguigu.model.entity.SystemUser;
import com.atguigu.model.enums.BaseStatus;
import com.atguigu.web.admin.mapper.SystemUserMapper;
import com.atguigu.web.admin.service.LoginService;
import com.atguigu.web.admin.service.SystemUserService;
import com.atguigu.web.admin.vo.login.CaptchaVo;
import com.atguigu.web.admin.vo.login.LoginVo;
import com.atguigu.web.admin.vo.system.user.SystemUserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import io.jsonwebtoken.Claims;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private SystemUserMapper systemUserMapper;
    @Autowired
    private SystemUserService systemUserService;

    @Override
    public CaptchaVo getCaptcha() {
//        1.生成验证码（从easy-captcha依赖来的功能）
        SpecCaptcha specCaptcha = new SpecCaptcha(130,48,4);
//        设置验证码的字符类型
        specCaptcha.setCharType(Captcha.TYPE_DEFAULT);
        String imageBase64 = specCaptcha.toBase64();
//        将验证码图片转码成正确的验证码字符串
        String code = specCaptcha.text();

//        2.将正确验证码的值+uuid存储到redis中
        String uuidKey = RedisConstant.ADMIN_LOGIN_PREFIX+UUID.randomUUID().toString().replaceAll("-","");
        redisTemplate.opsForValue().set(uuidKey,code,RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.MINUTES);

//        3.拼接captchaVo
        CaptchaVo captchaVo = new CaptchaVo(imageBase64,uuidKey);
        return captchaVo;

    }

    @Override
    public String login(LoginVo loginVo) {
        // 1. 判断前端是否输入了验证码
        if (!StringUtils.hasText(loginVo.getCaptchaCode())) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
        }

        // 2. 校验验证码
        String code = (String) redisTemplate.opsForValue().get(loginVo.getCaptchaKey());
        if (code == null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }

        // 将用户输入和存储的验证码都转为小写进行比较
        if (!code.toLowerCase().equals(loginVo.getCaptchaCode().toLowerCase())) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }

        // 验证成功后删除验证码，防止重复使用
        redisTemplate.delete(loginVo.getCaptchaKey());

        // 3. 校验用户是否存在
        LambdaQueryWrapper<SystemUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemUser::getUsername, loginVo.getUsername());
        SystemUser systemUser = systemUserMapper.selectOne(queryWrapper);
        if (systemUser == null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }

        // 4. 校验用户是否被禁止
        if (systemUser.getStatus() == BaseStatus.DISABLE) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }

        // 5. 校验用户密码
        if (!systemUser.getPassword().equals(DigestUtils.md5Hex(loginVo.getPassword()))) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }

        // 6. 创建并返回TOKEN
        return JwtUtil.createToken(systemUser.getId(), systemUser.getUsername());
    }

    @Override
    public SystemUserInfoVo customInfo(String accessToken) {
        // 1. 从前端传来的token获取claims
        Claims claims = JwtUtil.parseToken(accessToken);

        // 2. 从token的claims里面获取userId
//        claim会将其中的整数都弄成Integer类型，这里用integer类接取
        Integer userId = (Integer) claims.get("userId");

        // 3. 根据userId查询后端用户数据
        SystemUser systemUser = systemUserService.getById(userId.longValue());

        // 4. 把后端用户数据打包成SystemUserInfoVo数据结构返回给前端用户
        SystemUserInfoVo systemUserInfoVo = new SystemUserInfoVo();
        systemUserInfoVo.setName(systemUser.getName());
        systemUserInfoVo.setAvatarUrl(systemUser.getAvatarUrl());

        return systemUserInfoVo;
    }
}
